/** @ingroup tool Tool
 * @{
 */

/*
 * Application\Src\xstring.c
 *
 * String libarary function
 *
 * Author: Chao-Chi Kuo <chaochi_kuo@systech.com.tw>
 * Copyright (c) 2010 SYSTEMS & TECHNOLOGY CORP. <http://www.systech.com.tw/>
 * All rights reserved.
 *
 * Modifications:
 * 2009/11/18 Chao-Chi Kuo	first implemetation
 *
 * $Id: xstring.c 164 2010-07-15 10:01:44Z chaochi_kuo $
 */
#include "xstring.h"

/**
 * @brief	copies one buffer to another
 * @param	to		destination buffer
 * @param	from	source buffer
 * @param	count	length
 * @return	to
 * @note	
 */
void *xmemcpy(void *to, const void *from, size_t count)
{
	unsigned char *t = (unsigned char *)to;
	unsigned char *f = (unsigned char *)from;
	
	while (count--)
		*t++ = *f++;
	
	return to;
}

/**
 * @brief	fills a buffer with a character
 * @param	buffer	buffer
 * @param	ch		character
 * @param	count	length
 * @return	buffer
 * @note	
 */
void *xmemset(void *buffer, int ch, size_t count)
{
	unsigned char *b = (unsigned char *)buffer;
	
	while (count--)
		*b++ = ch;
		
	return buffer;
}

/**
 * @brief	concatenates two strings
 * @param	str1	string 1
 * @param	str2	string 2
 * @return	str1
 * @note	
 */
char *xstrcat(char *str1, const char *str2)
{
	char *s;
	
	for (s = str1; *s != '\0'; ++s)
		;
	for (;*str2 != '\0'; *s++ = *str2++)
		;
	*s = '\0';
	
	return str1;
}

/**
 * @brief	compares two strings
 * @param	str1	string 1
 * @param	str2	string 2
 * @return	less than 0		str1 is less than str2	\n
 *			equal to 0		str1 is equal to str2	\n
 *			greater than 0	str1 is greater than str2
 * @note	
 */
int xstrcmp(const char *str1, const char *str2)
{
	register signed char __ret;
	
	while (1)
	{
		if ((__ret = *str1++ - *str2++) != 0 || !*str1)
			break;
	}
	return __ret;
}


/**
 * @brief	finds the first occurrence of a character in a string
 * @param	str	string
 * @param	ch	character
 * @return	a pointer to the first occurence of ch in str, or NULL if ch is not found.
 * @note	
 */
char *xstrchr(const char *str, int ch)
{
	const char *p = str;
	while (*p != '\0')
	{
		if (*p == (char)ch)
			return (char *)p;
		p++;
	}
    return NULL;
}

/**
 * @brief	returns the length of a given string
 * @param	str	string
 * @return	the length of str (determined by the number of characters before null termination). Str may not be null
 * @note	
 */
size_t xstrlen( char *str )
{
	const char *s;
	
	for (s = str; *s != '\0'; ++s)
		;
	return (size_t)(s - str);
}
/** @} */